//
//  ViewController.m
//  ContactOf0825
//
//  Created by 韩震明 on 15/11/20.
//  Copyright © 2015年 韩震明. All rights reserved.
//

#import "ViewController.h"
#import <Masonry.h>
// 这个常量,就可以在使用Masonry不必总带着前缀 `mas_`:
#define MAS_SHORTHAND

// 定义这个常量,以支持在 Masonry 语法中自动将基本类型转换为 object 类型:
#define MAS_SHORTHAND_GLOBALS

#define ABCD @"ABCDEFGHIGKLMNOPQRSTUVWXYZ#"

#import "SyneminCoreDataManager.h"
#import "SyneminFirstPageTVC.h"
#import "SyneminDetailsVC.h"
#import "SyneminAddContactVC.h"
#import "ContactOf0825.h"

@interface ViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *arr;
@property (nonatomic, strong) NSMutableDictionary *sectionDic;
@property (nonatomic, strong) NSMutableArray *mebersOfSection;

@end

@implementation ViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.view.backgroundColor = [UIColor whiteColor];
    
    NSLog(@"%@", [[SyneminCoreDataManager defaults] applicationDocumentsDirectory]);
    
    [self createNavigation];
    
    [self createTableView];
  
    
}

#pragma mark - TableView Setting

- (void)createTableView
{
    self.tableView = [[UITableView alloc] init];
    [self.view addSubview:self.tableView];
    self.tableView.backgroundColor = [UIColor whiteColor];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
        
    }];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    [self.tableView registerClass:[SyneminFirstPageTVC class] forCellReuseIdentifier:@"reuse"];
    
}

#pragma mark - TableView Delegate Method

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    NSString *key = [NSString stringWithFormat:@"%c", [ABCD characterAtIndex:section]];
    return [[self.sectionDic objectForKey:key] count];
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SyneminFirstPageTVC *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse" forIndexPath:indexPath];
    
    NSString *key=[NSString stringWithFormat:@"%c",[ABCD characterAtIndex:indexPath.section]];
    
    self.arr = [self.sectionDic objectForKey:key];
    if (self.arr.count != 0) {
        ContactOf0825 *con = self.arr[indexPath.row];
        cell.nameLabel.text = con.name;
        cell.sexLabel.text = con.sex;
        cell.numberLabel.text = [NSString stringWithFormat:@"%@", con.number];
    }
    
    return cell;
}

- (nullable NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    UITableViewRowAction *firstAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        
        [[SyneminCoreDataManager defaults] deleteFromSelectFormatString:@"name" arguments:[self.arr[indexPath.row] name]];
        self.arr = [NSArray array];
        self.arr = [[SyneminCoreDataManager defaults] selectAll];
        [self.tableView reloadData];
        
    }];
    
    UITableViewRowAction *secondAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"编辑" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        SyneminDetailsVC *details = [[SyneminDetailsVC alloc] init];
        [self.navigationController pushViewController:details animated:YES];
        details.detailContact = self.arr[indexPath.row];
        
    }];
    secondAction.backgroundColor = [UIColor colorWithRed:1.0 green:0.7067 blue:0.8451 alpha:1.0];
    return @[firstAction, secondAction];
}

#pragma mark - Table View Section Method

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.sectionDic.count;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    NSString *key = [NSString stringWithFormat:@"%c",[ABCD characterAtIndex:section]];
    if ([[self.sectionDic objectForKey:key] count] !=0) {
        
        return key;
    }
    return nil;
}

// 检索右边栏
- (NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    NSMutableArray *arr = [NSMutableArray array];
    for (int i = 0; i < 26; i++) {
        NSString *str = [NSString stringWithFormat:@"%c", 'A' + i];
        [arr addObject:str];
    }
    [arr addObject:@"#"];
    return arr;
}

#pragma mark - Cell Did Selected Method

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    SyneminDetailsVC *detailsVC = [[SyneminDetailsVC alloc] init];
    [self.navigationController pushViewController:detailsVC animated:YES];
    
}

#pragma mark - Navigation

- (void)createNavigation
{
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addContact:)];
}

#pragma mark - Right Bar BUtton Click Method

- (void)addContact:(UIBarButtonItem *)rightButton
{
    SyneminAddContactVC *addVC = [[SyneminAddContactVC alloc] init];

    [self.navigationController pushViewController:addVC animated:YES];
}

#pragma mark - View Will Appear Method

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.arr = [[NSArray alloc] init];
    self.arr = [[SyneminCoreDataManager defaults] selectAll];
    
    self.mebersOfSection = [NSMutableArray array];
    for (int i = 0; i < 26; i++) {
        NSString *str = [NSString stringWithFormat:@"%c", 'A' + i];
        [self.mebersOfSection addObject:str];
    }
    [self.mebersOfSection addObject:@"#"];
    
    /**
     *  省市区字典分别把首字母与相应的数组放入字典中以便分区赋值和cell的赋值
     */
    // 初始化字典   必须初始化!!! 否则无法接受到值
    self.sectionDic = [NSMutableDictionary dictionary];
    if (self.arr.count != 0) {
        for (int i = 0; i < 26; i++) {
            NSMutableArray *tempArr = [NSMutableArray array];
            [self.sectionDic setObject:tempArr forKey:[NSString stringWithFormat:@"%c", 'A' + i]];
            for (ContactOf0825 *con in self.arr) {
                NSString *capital = [self transformMandarinToLatin:con.name];
                NSString *abc = [NSString stringWithFormat:@"%c", 'A' + i];
                if ([capital isEqualToString:abc]) {
                    [tempArr addObject:con];
                    [self.sectionDic setObject:tempArr forKey:abc];
                }
            }
        }
        [self.sectionDic setObject:[NSMutableArray array] forKey:@"#"];
    } else {
        for (int i = 0; i < 26; i++) {
            NSMutableArray *tempArr = [NSMutableArray array];
            [self.sectionDic setObject:tempArr forKey:[NSString stringWithFormat:@"%c", 'A' + i]];
            
        }
        [self.sectionDic setObject:[NSMutableArray array] forKey:@"#"];
    }
    
    [self.tableView reloadData];
}

#pragma mark - 转拼音

- (NSString*)transformMandarinToLatin:(NSString*)string
{
    
    NSMutableString*preString = [string mutableCopy];
    
    /*转换成成带音调的拼音*/
    CFStringTransform((CFMutableStringRef)preString,NULL,kCFStringTransformMandarinLatin,NO);
    
    /*去掉音调*/
    CFStringTransform((CFMutableStringRef)preString, NULL, kCFStringTransformStripDiacritics, NO);
    
    NSString *firstLetter = [preString substringToIndex:1];
    
    return  [firstLetter uppercaseString];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
